package com.ds.robot.assistant.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.google.common.collect.ImmutableMap;
import com.ds.robot.assistant.common.R;
import com.ds.robot.assistant.component.MilestoneReadListener;
import com.ds.robot.assistant.entity.ReqInfoEntity;
import com.ds.robot.assistant.enums.Env;
import com.ds.robot.assistant.job.MilestoneTipJob;
import com.ds.robot.assistant.job.YunXiaoBugTipJob;
import com.ds.robot.assistant.model.MilestoneData;
import com.ds.robot.assistant.service.ReqInfoService;
import com.ds.robot.assistant.service.ReqMilestonesService;
import com.ds.robot.assistant.vo.ReqMilestoneVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 需求相关接口
 *
 * @author WeiShaoying
 * @date 2024-08-01 20:46:34
 */
@RestController
@RequestMapping("/req")
@Slf4j
public class RequirementsController {

    @Autowired
    private ReqInfoService reqInfoService;

    @Autowired
    private ReqMilestonesService milestonesService;

    @Autowired
    private MilestoneTipJob milestoneTipJob;

    @Autowired
    private YunXiaoBugTipJob yunXiaoTipJob;

    public static final String MILESTONE_DATA = "里程碑数据";

    @RequestMapping("/list")
    public R list() {
        List<ReqInfoEntity> list = reqInfoService.list();
        return R.ok().put("data", list);
    }

    @RequestMapping("/query/today")
    public R queryMilestoneByDate() {
        yunXiaoTipJob.sendRequirementReport(false);
        return R.ok("请在企信群中查看需求统计报告");
    }

    @RequestMapping("/milestone/today")
    public R queryTodayMilestone() {
        milestoneTipJob.queryAndSendTodayReqMilestoneTip(Env.TEST);
        return R.ok();
    }

    @RequestMapping("/milestone/today/prod")
    public R queryTodayMilestoneProd() {
        milestoneTipJob.queryAndSendTodayReqMilestoneTip(Env.PROD);
        return R.ok();
    }

    @RequestMapping("/milestone/query/{date}")
    public R queryMilestoneByDate(@PathVariable("date") String date) {
        milestoneTipJob.queryAndSendReqMilestoneTipByDate(date, Env.TEST);
        return R.ok();
    }

    /**
     * 修改
     */
    @Deprecated
    @PostMapping("/milestone/update")
    public R modifyMilestone(@RequestBody ReqMilestoneVO vo) {
        if (Objects.isNull(vo) || Objects.isNull(vo.getId()) || !StringUtils.hasText(vo.getReqName())) {
            return R.error(400, "id, reqName不能为空");
        }
        // milestonesService.updateMilestone(vo);
        return R.ok("更新成功");
    }

    /**
     * 通过需求名称全部删除里程碑
     */
    @PostMapping("/milestone/delete")
    public R deleteMilestone(@RequestBody Map<String, String> map) {
        String reqName = map.get("reqName");
        if (!StringUtils.hasText(reqName)) {
            return R.error(400, "reqName不能为空");
        }
        milestonesService.deleteByReqName(reqName);
        return R.ok("删除成功");
    }


    @PostMapping("/milestone/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try (InputStream inputStream = file.getInputStream()) {
            EasyExcel.read(inputStream, MilestoneData.class, new MilestoneReadListener(milestonesService))
                    .sheet(0)
                    .headRowNumber(2) // 设置表头所在的行号，这里是从第二行开始
                    .doRead();
            return ResponseEntity.ok("里程碑上传成功");
        } catch (Exception e) {
            log.error("里程碑上传失败", e);
            return ResponseEntity.status(500).body("里程碑上传失败:" + e.getMessage());
        }
    }

    @GetMapping("/milestone/download")
    public void download(HttpServletResponse response) throws IOException {
        // 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 防止中文乱码
        String fileName = URLEncoder.encode(MILESTONE_DATA + "_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss")), "UTF-8")
                .replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        InputStream inputStream = getClass().getClassLoader().getResourceAsStream("doc/里程碑模板.xlsx");
        List<MilestoneData> dataList = milestonesService.queryAllData();

        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().sheetName(MILESTONE_DATA).build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照下一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(dataList, fillConfig, writeSheet);
            Map<String, Object> map = ImmutableMap.of("total", dataList.size());
            excelWriter.fill(map, writeSheet);
        }
    }


}
